package org.grow.stable.security;

import org.grow.stable.security.dao.PermissionDao;
import org.grow.stable.security.domain.Permission;
import org.grow.stable.security.domain.Role;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotAccessDecisionMaker extends RoleVoter implements FilterInvocationSecurityMetadataSource {

    @Resource
    private PermissionDao permissionDao;
    @Resource
    private EntityManager entityManager;

    //DataSource接口
    @SuppressWarnings("deprecation")
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        /*String s = "select r.role from permission p\n" +
                "left join permission_role r\n" +
                "    on p.permission_id = r.permission_id_fk\n" +
                "where p.path like";
        Query results = entityManager.createNativeQuery(s + " '" + request.getRequestURI() + "' ",String.class);
        List resultList = results.getResultList();*/
        System.out.println(request.getRequestURI());
        Permission p = permissionDao.findByPath(request.getRequestURI());
        if (p==null){
              throw new RuntimeException("no this path sorry") ;
        }
        System.out.println(p);
        return p.getRoles().stream()
                .map(e->new SecurityConfig(e.toString()))
                .collect(Collectors.toList());
        //return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return Arrays.asList(Role.values())
                .stream().map(e->new SecurityConfig(e.toString()))
                .collect(Collectors.toList());

     //   return null;
    }
    //vote 接口

    @Override
    public int vote(Authentication authentication, Object object,
                    Collection<ConfigAttribute> attributes) {
        return super.vote(authentication,object,attributes);

    }

    @Override
    public boolean supports(Class<?> clazz) {
        return super.supports(clazz);
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }
}
